package org.opens.shiro;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.opens.base.Const;
import org.opens.dao.ShiroUserDao;
import org.opens.entity.ShiroPermission;
import org.opens.entity.ShiroRole;
import org.opens.entity.ShiroUser;
import org.opens.service.ShiroPermissionService;
import org.opens.service.ShiroRoleService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Realm extends AuthorizingRealm {

    @Autowired
    private ShiroUserDao shiroUserDao;

    @Autowired
    private ShiroRoleService shiroRoleService;

    @Autowired
    private ShiroPermissionService shiroPermissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        ShiroUser user = ((ShiroUser) principals.getPrimaryPrincipal());

        List<ShiroRole> roles = shiroRoleService.findByUserId(user.getId());
        List<ShiroPermission> permissions = shiroPermissionService.findByRoleIn(roles);

        Set<String> rolesName = new HashSet<>();
        Set<String> competences = new HashSet<>();

        if (CollectionUtil.isNotEmpty(roles)) {
            rolesName.addAll(roles.stream().map(ShiroRole::getName).collect(Collectors.toList()));
        }
        if (CollectionUtil.isNotEmpty(permissions)) {
            competences.addAll(permissions.stream().map(ShiroPermission::getName).collect(Collectors.toList()));
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(competences);
        simpleAuthorizationInfo.setRoles(rolesName);

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        String userName = userToken.getUsername();
        ShiroUser user = shiroUserDao.findByName(userName);
        if (user == null) {
            throw new AccountException("此用户不存在!");
        }
        if (user.getStatus() == Const.USER_LOCK) {
            throw new LockedAccountException(user.getName() + "被锁定");
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes("ewaytek"),  getName());
        return simpleAuthenticationInfo;
    }
}
